/**
 * 检查FORM表单[Value]值
 * @param $rule
 * @param $value
 * @param $callback
 */
var formRuleForValue = function ($rule, $value, $callback) {

    var vueInstance = window.instance;
    var valStage = $w.dataNoBind($value);
    if ($value instanceof Object || $value instanceof Array) {
        valStage = JSON.stringify(valStage);
    }
    // 长度 - 数组、非对象
    if (vueInstance.form.length && parseInt(vueInstance.form.length) !== 0 &&
        valStage.length > vueInstance.form.length
    ) {
        return $callback(new Error('值长度大于' + vueInstance.form.length + '字符'));
    }
    // 正则
    if (!$w.isEmpty(vueInstance.form.reg) && !vueInstance.execReg(valStage, true)) {
        return $callback(new Error('正则验证未通过'));
    }
    // 值类型[JSON]
    if (vueInstance.form.type === vueInstance.setting.type_list.json.value && !$w.isJson($value)) {
        // return $callback(new Error('不是合法的JSON值，如：{"KEY":"1",VALUE:"开启"}'));
    }

    return $callback();
};

/**
 * [站点设置]表单[JS]
 * @returns {*}
 */
var app = function ($isCreate) {

    return new Vue({
        el: '#vueContainer',
        data: {
            loadOver: false,
            detailOver: false,
            settingOver: false,
            setting: {
                pageType: 'form',    // 页面类型
                isCreate: $isCreate, // 添加状态
            },
            form: {
                key: null,
                title: null,
                value: '',
                option: {},
                group: null,
                status: null,
                type: 0,
                length: 0,
                reg: null,
                hint: null,
                description: null,
                is_required: 0,
                sort: 0,
                top_line: 0,
                top_title: null,
                unit: null,
                width: null
            },
            oldKey: null,  // 给更新用[key]字段值
            customErrMsg: {}, // 自定义错误列表
            localType: 'text', // 当前选择字段类型(前端自用)
            pageDialog: {
                show: false,    // 页面 - 是否展示弹出层
                url: '',        // 页面 - 弹出层连接
                loading: false, // 页面 - 弹出层加载中
                isIframe: false // 页面 - 是否[iframe]嵌入
            },
        },
        created: function () {
            // 初始化
            this.init();
            // 初始化下设置
            this.getSetting();
            var that = this;
            this.$nextTick(function () {
                that.loadOver = true;
                that.initMainScroll();
            });
        },
        methods: {
            /**
             * 初始化的逻辑
             */
            init: function () {

                var params = $w.getParams();
                // 是否[iframe]嵌入
                this.pageDialog.isIframe = window.self !== window.top;

                var that = this;
                // [嵌入]返回事件监听 直接走自己的返回
                if (this.pageDialog.isIframe) {
                    window.addEventListener("popstate", function($event) {
                        if (that.cancel) that.cancel(); // 返回上一页
                        window.history.forward(-1);     // 清理此页历史记录
                    }, false);
                    window.history.pushState({
                        title: "title", url: "#"
                    }, "title", "#");
                    window.history.forward(1);
                }
            },
            /**
             * 初始化滚动条
             */
            initMainScroll: function () {
                var shadowDom = this.$refs['mainScrollShadow'];
                if (!shadowDom) return false;
                this.$refs.mainScroller.wrap.onscroll = function ($event) {
                    var opacity = 0;
                    opacity = $event['srcElement']['scrollTop'] / 100;
                    opacity = opacity > 0.6 ? 0.6 : opacity
                    shadowDom['$el']['style']['box-shadow'] = '0 5px 15px 0 rgb(204, 204, 204, ' + opacity + ')';
                };
            },
            /**
             * 获取设置
             * @returns {boolean}
             */
            getSetting: function () {
                // 正在加载...
                var loadingInstance = ELEMENT.Loading.service({
                    fullscreen: false,
                    text: '加载中...',
                    customClass: 'z-index-top'
                });
                var that = this;

                // 获取各模块的值
                $w.request({
                    url: $w.getApiUrl('setting.setting'),
                    type: 'get',
                    data: {
                        type: 'form' // 表单页
                    },
                    dataType: 'json',
                    afterCallback: function () {
                        that.$nextTick(function () {
                            // 设置记载完毕
                            that.settingOver = true;
                            // 初始化、获取详情
                            that.initDetail();
                            // 隐藏正在加载
                            loadingInstance.close();
                        });
                    },
                    callback: function (event) {

                        // 失败的返回|提示
                        if (parseInt(event.no) !== 200) {

                            return that.$message({
                                showClose: true,
                                type: 'error',
                                message: event.msg ? event.msg : '操作失败，请稍后尝试'
                            });
                        }

                        // 挨个赋值[setting]中
                        var filters = ['value_need_opt_list'];
                        for (var i in event.data) {
                            if (!event.data.hasOwnProperty(i)) continue;

                            that.$set(that.setting, i, event.data[i]);

                            // 在过滤列表中进行过滤
                            if ($w.in_array(i, filters)) continue;
                            // 改变键值
                            if (i.indexOf('_list') !== -1) {
                                that.setting[i] = $w.array_index(event.data[i], 'key');
                            }

                            // 默认值
                            if (i.indexOf('default_') !== -1 && that.setting.isCreate) {
                                that.form[i.replace('default_', '')] = that.setting[i];
                            }
                        }
                    }
                });
            },
            /**
             * 获取下详细信息
             */
            initDetail: function () {

                // 正在加载。。
                var loadingInstance = ELEMENT.Loading.service({
                    fullscreen: false,
                    text: '获取中...',
                    customClass: 'z-index-top'
                });
                var that = this;

                // 是新建
                if ($isCreate) {

                    this.detailOver = true; // 详情加载完毕
                    return loadingInstance.close();
                }

                // 获取各模块的值
                $w.request({
                    url: $w.getApiUrl('setting.detail'),
                    type: 'get',
                    data: {id: $w.getParams('id')},
                    dataType: "json",
                    beforeCallback: function () {
                        that.$nextTick(function () {
                            // 详情加载完毕
                            that.detailOver = true;
                            // 隐藏正在加载
                            loadingInstance.close();
                            // 更新下选择类型信息
                            that.changeType();
                        });
                    },
                    callback: function (event) {

                        // 失败的返回|提示
                        if (parseInt(event.no) !== 200) {

                            return that.$message({
                                showClose: true,
                                type: 'error',
                                message: event.msg ? event.msg : '操作失败，请稍后尝试'
                            });
                        }

                        that.form = event.data;
                        that.oldKey = that.form.key;
                    }
                },);
            },
            /**
             * 字段类型改变
             * @returns {string}
             */
            changeType: function () {

                if (!this.settingOver) return this.localType = 'text';
                var type = this.form.type + '';
                // 添加条目类型
                var addRows = this.setting.value_need_opt_list;
                if ($w.in_array(type, addRows)) return this.localType = 'addRow';
                // JSON 类型
                // if (type === this.setting.type_list.json + '') return this.localType = 'json';
                // 文本编辑器类型
                if (type === this.setting.type_list.html.value + '') {

                    return this.localType = 'html';
                }
                // 图片类型
                if (type === this.setting.type_list.image.value + '') {
                    // 判断不是合法文件，置空
                    if (!$w.isImageUrl(this.form.value)) this.$nextTick(function () {
                        this.$refs['uploader_form_value_image'].handleRemoveItem();
                    });
                    return this.localType = 'image';
                }
                // excel类型
                if (type === this.setting.type_list.excel.value + '') {
                    // 判断不是合法文件，置空
                    if (!$w.isExcelUrl(this.form.value)) this.$nextTick(function () {
                        this.$refs['uploader_form_value_excel'].handleRemoveItem();
                    });
                    return this.localType = 'excel';
                }

                // 其他返回文本
                return this.localType = 'text';
            },
            /**
             * 返回上一页
             * @param $reloadList 需要加载列表
             */
            cancel: function ($reloadList) {

                // 需要重新加载下列表
                if ($reloadList && this.pageDialog.isIframe && window.parent.instance.getList) {
                    window.parent.instance.getList();
                }

                // 显示脚部 - 当前页面返回
                if (!this.pageDialog.isIframe) {
                    // 非嵌入页面暂不操作 - 可根据逻辑自行修改
                    // // 正在加载。。
                    // var loadingInstance = ELEMENT.Loading.service({
                    //     fullscreen: false,
                    //     text: '返回中...',
                    //                     customClass: 'z-index-top'
                    // });
                    // window.history.back();
                } else {
                    window.parent.instance.pageDialog.show = false;
                }
            },
            /**
             * 去首页
             */
            goToIndex: function () {
                // 父级
                var parent = window.parent.top;
                if (!parent) return false;

                // 父级[vue]对象
                var vueInstance = parent.instance;
                if (!parent || !(typeof vueInstance === 'object')) return false;

                // 键值
                var key = vueInstance.tab.indexKey;
                // 操作点击
                $(parent.document).find('#tab-' + key).click();
            },
            /**
             * 添加
             */
            submit: function () {

                var that = this;

                // 酌情检测施行编辑器里的值
                var data = that.formatFormValue();
                // 清空错误信息
                this.$set(that, 'customErrMsg', {});
                this.$refs['ruleForm'].validate(function (valid, msg) {

                    // 验证不过 - 滚动到错误字段
                    if (!valid) {
                        var first = $w.array_first_key(msg);
                        return $w.scrollToFormItem(false, first);
                    }

                    // 连接
                    var url = that.setting.isCreate ?
                        $w.getApiUrl('setting.create') :
                        $w.getApiUrl('setting.update');

                    // 正在加载。。
                    var loadingInstance = ELEMENT.Loading.service({
                        fullscreen: false,
                        text: '正在提交...',
                        customClass: 'z-index-top'
                    });

                    $w.request({
                        url: url,
                        type: 'POST',
                        data: data,
                        dataType: "json",
                        beforeCallback: function () {
                            that.$nextTick(function () {
                                // 隐藏正在加载
                                loadingInstance.close();
                            });
                        },
                        callback: function (event) {

                            // 失败的返回|提示
                            if (parseInt(event.no) !== 200) {
                                for (var i in event.data.column_error) {
                                    if (!event.data.column_error.hasOwnProperty(i))
                                        continue;
                                    that.$set(that.customErrMsg, i, event.data.column_error[i]);
                                }
                                // 滚动到错误字段
                                $w.scrollToFormItem();
                                return that.$message({
                                    showClose: true,
                                    type: 'error',
                                    message: event.msg ? event.msg : '操作失败，请稍后尝试'
                                });
                            }

                            // 返回上一页
                            that.cancel(true);
                        }
                    });
                });
            },
            /**
             * 格式化[FORM]值
             * @returns {*}
             */
            formatFormValue: function () {

                var fieldType = this.form.type;
                //**** 编辑机器返回编辑器内容 ****
                // 类型为条目
                if (fieldType === this.setting.type_list.html.value) {
                    this.form.value = this.$refs['html_editor'].getEditorHtml();
                }

                return $w.dataNoBind(this.form);
            },
            /**
             * 添加一条键值数据
             * @param $column 字段
             */
            addRowValue: function ($column) {

                if ($column === 'value' && $w.isEmpty(this.form['option'])) return this.$message({
                    showClose: true,
                    type: 'error',
                    message: event.msg ? event.msg : '请先添加字段信息'
                });

                if ($w.isEmpty(this.form[$column])) {
                    this.$set(this.form, $column, []);
                }

                // 基础数据
                var key = this.form[$column].length, data = {};
                // 字段为[值]
                if ($column === 'value') for (var i in this.form.option) {
                    if (!this.form.option.hasOwnProperty(i)) continue;
                    data[this.form.option[i]['key']] = '';
                } else { // 字段为[选项]
                    data = {key: '', text: ''};
                }
                this.$set(this.form[$column], !key ? 0 : key, data);
            },
            /**
             * 上移一条数据
             * @param $key
             * @param $column
             */
            upRowValue: function ($key, $column) {

                var stage = $w.dataNoBind(this.form[$column]);
                // 条目总长度
                var dataLength = 1;
                // 对象需要转化下
                if (!stage instanceof Array) {
                    $key = Object.keys($w.dataNoBind(stage)).indexOf($key);
                }

                // 已经是最后一个
                if (parseInt($key) === (dataLength - 1)) {
                    return this.$message({
                        type: 'error',
                        showClose: true,
                        message: '已经是第一个啦'
                    });
                }

                this.$set(this.form, $column, $w.array_sort(stage, $key, $key - 1));
            },
            /**
             * 下移一条数据
             * @param $key
             * @param $column
             */
            downRowValue: function ($key, $column) {

                var stage = $w.dataNoBind(this.form[$column]);
                // 条目总长度
                var dataLength = 0;
                // 对象需要转化下
                if (!stage instanceof Array) {
                    $key = Object.keys($w.dataNoBind(stage)).indexOf($key);
                    dataLength = Object.keys($w.dataNoBind(stage)).length;
                } else {
                    dataLength = stage.length;
                }
                // 已经是最后一个
                if ($key === (dataLength - 1)) {
                    return this.$message({
                        type: 'error',
                        showClose: true,
                        message: '已经是最后一个啦'
                    });
                }


                this.$set(this.form, $column, $w.array_sort(stage, $key, $key + 1));
            },
            /**
             * 删除一条键值数据
             * @param $key
             * @param $column
             */
            delRowValue: function ($key, $column) {

                var that = this;
                this.$confirm('此操作将[删除]此条数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {

                    that.$delete(that.form[$column], $key);
                });
            },
            /**
             * 清空全部据
             * @param $column
             */
            cleanAll: function ($column) {
                if ($w.isEmpty(this.form[$column])) return this.$message({
                    type: 'error',
                    showClose: true,
                    message: '值列表为空无需清除'
                });

                var that = this;
                this.$confirm('此操作将[删除]全部数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {

                    that.$set(that.form, $column, []);
                });
            },
            /**
             * 执行正则验证
             */
            execReg: function ($value, $returnBool) {

                if (!$value || $w.isEmpty($value)) {
                    $value = $w.dataNoBind(this.form.value);
                }
                // 正则为空
                if ($w.isEmpty(this.form.reg)) return $returnBool ?
                    false : this.$set(this.customErrMsg, 'reg', '请完验证正则');

                // 暂存正则
                var reg = $w.dataNoBind(this.form.reg);
                // 需要去掉第一个/
                if (reg.substr(0, 1) === '/') {
                    reg = reg.substr(1, reg.length);
                }
                // 需要去掉最后一个/
                if (reg.substr(reg.length - 1, reg.length) === '/') {
                    reg = reg.substr(0, reg.length - 1);
                }
                reg = new RegExp(reg);
                // 验证不过
                if (!reg.test($value)) return $returnBool ?
                    false : this.$message({
                        type: 'error',
                        showClose: true,
                        message: '字段值正则验证不通过'
                    });

                return $returnBool ? true : this.$message({
                    type: 'success',
                    showClose: true,
                    message: '字段值正则验证通过'
                });
            },
            /**
             * 获取[JSON]字段值列表中[class]
             * @param $item
             * @param $key
             * @returns {string}
             */
            getJsonClass: function ($item, $key) {
                var classStr = [];
                var keyLen = Object.keys($item);
                var index = keyLen.indexOf($key);
                // 保证第一个有边框
                if (((index + 1) % 4) === 0 || (index + 1) === 1) {
                    classStr.push('border-left');
                }
                // 保证第三个没右侧边框
                if (this.form.can_add_row === this.setting.can_add_row_list.yes.value &&
                    (index + 1) % 3 === 0
                ) {
                    classStr.push('no-border-right');
                }
                // 展示添加按钮
                var keyLength = Object.keys(this.form.value).length;
                if (keyLength === (index + 1) && (index + 1) % 3 === 0) {
                    classStr.push('no-border-right');
                }
                return classStr.join(' ');
            },
            /**
             * 获取[JSON]栅格化每行几格
             */
            getJsonSpan: function () {
                var len = !this.form.option ? 0 : this.form.option.length,
                    total = 24 - 3;
                return $w.format_number(total / len, 0, 2);
            },
        },
        computed: {
            /**
             * 是否可添加条目-针对[JSON]类型
             * @returns {boolean}
             */
            isCanAddRow: function () {
                return +this.form.can_add_row === +this.setting.can_add_row_list.yes.value;
            },
            /**
             * 规则
             */
            formRules: function () {
                if (!this.detailOver) return {};
                return {
                    key: [
                        {required: true, message: '请完善字段名称', trigger: 'blur'},
                        {
                            pattern: /[0-9a-zA-Z_]*/, message: '只允许大小写字母、数字、下划线',
                            trigger: 'blur'
                        }
                    ],
                    title: [
                        {required: true, message: '请完善字段标题', trigger: 'blur'}
                    ],
                    value: [
                        {required: true, message: '请完善字段值', trigger: 'blur'},
                        {validator: formRuleForValue, trigger: 'blur'}
                    ],
                    option: [],
                    group: [
                        {required: true, message: '请完善所在分组', trigger: 'blur'}
                    ],
                    status: [
                        {required: true, message: '请完善状态', trigger: 'blur'}
                    ],
                    type: [
                        {required: true, message: '请完善字段类型', trigger: 'blur'}
                    ],
                    length: [
                        {required: true, message: '请完善字段长度', trigger: 'blur'}
                    ],
                    is_required: [
                        {required: true, message: '请选择是否必填', trigger: 'blur'}
                    ],
                    sort: [
                        {required: true, message: '请完善排序', trigger: 'blur'},
                        {type: 'number', message: '排序必须为整数', trigger: 'blur'},
                        {
                            validator: $w.validateNumRange, message: false, trigger: 'blur',
                            max: this.setting.max_sort, min: this.setting.min_sort
                        },
                    ],
                    top_line: [
                        {required: true, message: '请选择底部是否分割线', trigger: 'blur'}
                    ],
                }
            }
        },
        watch: {
            /**
             * 检测[type]
             * @param $value
             */
            'form.type': function ($value) {

                var that = this;
                // 最后出现可能空字符转为[null]
                if (this.form.value === 'null') this.form.value = null;

                // 非[JSON]类型 -> [JSON]类型
                var jsonType = this.setting.type_list.json.value,
                    valueType = typeof this.form.value;
                if (this.form.type === jsonType && valueType !== 'object') {
                    this.$set(this.form, 'value', {});
                }

                // [JSON]类型 -> 非[JSON]类型
                if (this.form.type !== jsonType && valueType === 'object') {
                    this.$set(this.form, 'value', JSON.stringify($w.dataNoBind(this.form.value)));
                }

                // 文本编辑器逻辑，如果是选择的文本编辑器
                if (this.setting.type_list && $value === this.setting.type_list.html.value) {
                    this.$nextTick(function () {

                        // that.initEditor('form.value', that.form.value);
                    })
                } else if ($value !== this.setting.type_list.html.value) {
                    // 选择的文本编辑器 编辑器变量还有 销毁
                    // this.form.value = this.$refs['html_editor'].getEditorHtml('form.value');
                    // this.editorObj.destroy();
                }
            }
        }
    });
};

